package com.wanxi.config;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ResultDto;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Li
 * @Date 2023/5/16 15:46
 */
@WebFilter("/*")
public class Filter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        //        1.乱码处理
        req.setCharacterEncoding("UTF-8");
        res.setCharacterEncoding("UTF-8");
//        2.一些敏感信息过滤
        String path = req.getServletPath();
//        System.out.println(path);
//        判断访问地址是否以back开头，如果是则判断是否以及登录
        if (path.startsWith("/back/")) {
//            String username = req.getParameter("loginName");
            Object username = req.getSession().getAttribute("username");
            if (username == null) {
// 跳转到登录页面
                res.sendRedirect("/html/login.html");
//                如果前后端分离
//                res.getWriter().println(JSONObject.toJSONString(ResultDto.builder()
//                        .code(400)
//                        .msg("未登录")
//                        .data(null)
//                        .build()));
            } else {
                chain.doFilter(req, res);//放行
            }
        } else {
            chain.doFilter(req, res);//放行
        }
    }
}
